package template

import (
	"errors"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/db"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/util"
	"time"
)

type Template struct {
	Id        int64     `json:"id"`
	Content   string    `json:"content"`
	Remarks   string    `json:"remark"`
	CreatedTs time.Time `json:"cteat_time"`
}

func insertTemplate(template *Template) error {
	sessionInstance := db.Session()
	defer sessionInstance.Close()
	sessionInstance.Begin()
	if _, err := sessionInstance.Insert(template); err != nil {
		sessionInstance.Rollback()
		global.Log.Sugar().Error("插入模板失败", err)
		return errors.New("插入模板失败")
	}
	sessionInstance.Commit()
	return nil
}

func updateTemplate(template *Template) error {
	sessionInstance := db.Session()
	defer sessionInstance.Close()
	sessionInstance.Begin()
	if _, err := sessionInstance.Where("id = ?", template.Id).Update(template); err != nil {
		sessionInstance.Rollback()
		return err
	}
	sessionInstance.Commit()
	return nil
}

func PutTemplate(template *Template) error {
	template.CreatedTs = time.Now()
	if template.Id != 0 {
		return updateTemplate(template)
	} else {
		template.Id = util.GenSnowflakeInt64()
		return insertTemplate(template)
	}
}

func DelTemplate(templateId int64) error {
	sessionInstance := db.Session()
	defer sessionInstance.Close()
	sessionInstance.Begin()
	if _, err := sessionInstance.Where("id = ?", templateId).Delete(new(Template)); err != nil {
		sessionInstance.Rollback()
		return err
	}
	sessionInstance.Commit()
	return nil
}

func GetTemplate(id int64, page, pagesize int) (int, []*Template, error) {
	sessionInstance := db.Session()
	defer sessionInstance.Close()
	offset := (page - 1) * pagesize
	if id != 0 {
		sessionInstance = sessionInstance.And("id=?", id)
	}
	if pagesize == 0 {
		pagesize = 10
	}
	templates := []*Template{}
	count, err := sessionInstance.
		Limit(pagesize, offset).
		FindAndCount(&templates)
	if err != nil {
		return 0, nil, err
	}
	return int(count), templates, nil
}
